package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.controller.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("CrawlerfileRestController")
public class CrawlerfileRestController extends CmiEmaController {

	/**
	 * Create a new Crawlerfile entity
	 * 
	 */
	@RequestMapping(value = "/newCrawlerfile", method = RequestMethod.POST)
	@ResponseBody
	public Object newCrawlerfile(@RequestBody Crawlerfile crawlerfile) {
		crawlerfileService.saveCrawlerfile(crawlerfile);
		return JSONObject
				.parse(cmiPsonService.toJsonString(crawlerfileDAO.findCrawlerfileByPrimaryKey(crawlerfile.getId()), 2));
	}

	@RequestMapping(value = "/restNewCrawlerfile", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewCrawlerfile(@RequestBody String crawlerfileJson) {
		Crawlerfile crawlerfile = new Gson().fromJson(crawlerfileJson, Crawlerfile.class);
		appendReferences(crawlerfile);
		crawlerfileService.saveCrawlerfile(crawlerfile);
		return JSONObject
				.parse(cmiPsonService.toJsonString(crawlerfileDAO.findCrawlerfileByPrimaryKey(crawlerfile.getId()), 2));
	}

	@RequestMapping(value = "/saveCrawlerfile", method = RequestMethod.PUT)
	@ResponseBody
	public Crawlerfile saveCrawlerfile(@RequestBody Crawlerfile crawlerfile) {
		crawlerfileService.saveCrawlerfile(crawlerfile);
		return crawlerfileDAO.findCrawlerfileByPrimaryKey(crawlerfile.getId());
	}

	@RequestMapping(value = "/restSaveCrawlerfile", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveCrawlerfile(@RequestBody String crawlerfileJson) {
		Crawlerfile crawlerfile = new Gson().fromJson(crawlerfileJson, Crawlerfile.class);
		appendReferences(crawlerfile);
		CmiPsonService cmiPsonService = new CmiPsonService();
		crawlerfileService.saveCrawlerfile(crawlerfile);
		return JSONObject
				.parse(cmiPsonService.toJsonString(crawlerfileDAO.findCrawlerfileByPrimaryKey(crawlerfile.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteCrawlerfile/{crawlerfileId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteCrawlerfile(@PathVariable Integer crawlerfileId) {
		Crawlerfile crawlerfile = crawlerfileDAO.findCrawlerfileByPrimaryKey(crawlerfileId);
		crawlerfileService.deleteCrawlerfile(crawlerfile);
	}

	@RequestMapping(value = "/restConfirmDeleteCrawlerfiles")
	@ResponseBody
	public Object restConfirmDeleteCrawlerfiles(@RequestBody Set<Integer> deleteCrawlerfilesIds) {
		Set<Crawlerfile> deleteCrawlerfiles = crawlerfileDAO.findCrawlerfilesByIds(deleteCrawlerfilesIds);
		Set<Crawlerfile> referencedCrawlerfiles = crawlerfileService.loadReferenceCrawlerfiles(deleteCrawlerfiles);
		deleteCrawlerfiles.removeAll(referencedCrawlerfiles);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedCrawlerfiles);
		jsonObject.put("deleteEntitys", deleteCrawlerfiles);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteCrawlerfiles")
	@ResponseBody
	public Object restDeleteCrawlerfiles(@RequestBody Set<Crawlerfile> deleteCrawlerfiles) {
		Iterator<Crawlerfile> iterator = deleteCrawlerfiles.iterator();
		while (iterator.hasNext()) {
			Crawlerfile currentCrawlerfile = iterator.next();
			crawlerfileService.deleteCrawlerfile(currentCrawlerfile);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listCrawlerfiles");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadCrawlerfile/{crawlerfileId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadCrawlerfile(@PathVariable Integer crawlerfileId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(crawlerfileDAO.findCrawlerfileByPrimaryKey(crawlerfileId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadCrawlerfileUrl/{crawlerfileId}/url", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadCrawlerfileUrl(@PathVariable Integer crawlerfileId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(crawlerfileDAO.findCrawlerfileByPrimaryKey(crawlerfileId).getUrl(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadCrawlerfileFiletype/{crawlerfileId}/filetype", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadCrawlerfileFiletype(@PathVariable Integer crawlerfileId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(crawlerfileDAO.findCrawlerfileByPrimaryKey(crawlerfileId).getFiletype(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadCrawlerfileCrawlerfilestatus/{crawlerfileId}/crawlerfilestatus", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadCrawlerfileCrawlerfilestatus(@PathVariable Integer crawlerfileId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				crawlerfileDAO.findCrawlerfileByPrimaryKey(crawlerfileId).getCrawlerfilestatus(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadCrawlerfileCrawlerfilestandard/{crawlerfileId}/crawlerfilestandard", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadCrawlerfileCrawlerfilestandard(@PathVariable Integer crawlerfileId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				crawlerfileDAO.findCrawlerfileByPrimaryKey(crawlerfileId).getCrawlerfilestandard(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	public void appendReferences(Crawlerfile crawlerfile) {

		Url url = crawlerfile.getUrl();
		if (url != null)
			crawlerfile.setUrl(urlService.findUrlByPrimaryKey(url.getId()));

		Filetype filetype = crawlerfile.getFiletype();
		if (filetype != null)
			crawlerfile.setFiletype(filetypeService.findFiletypeByPrimaryKey(filetype.getId()));

		Crawlerfilestatus crawlerfilestatus = crawlerfile.getCrawlerfilestatus();
		if (crawlerfilestatus != null)
			crawlerfile.setCrawlerfilestatus(
					crawlerfilestatusService.findCrawlerfilestatusByPrimaryKey(crawlerfilestatus.getId()));

		Crawlerfilestandard crawlerfilestandard = crawlerfile.getCrawlerfilestandard();
		if (crawlerfilestandard != null)
			crawlerfile.setCrawlerfilestandard(
					crawlerfilestandardService.findCrawlerfilestandardByPrimaryKey(crawlerfilestandard.getId()));

	}

	@RequestMapping(value = "/restGetCrawlerfileUrl/{crawlerfileId}/url", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetCrawlerfileUrl(@PathVariable Integer crawlerfileId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(crawlerfileDAO.findCrawlerfileByPrimaryKey(crawlerfileId).getUrl(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetCrawlerfileFiletype/{crawlerfileId}/filetype", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetCrawlerfileFiletype(@PathVariable Integer crawlerfileId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(crawlerfileDAO.findCrawlerfileByPrimaryKey(crawlerfileId).getFiletype(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetCrawlerfileCrawlerfilestatus/{crawlerfileId}/crawlerfilestatus", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetCrawlerfileCrawlerfilestatus(@PathVariable Integer crawlerfileId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				crawlerfileDAO.findCrawlerfileByPrimaryKey(crawlerfileId).getCrawlerfilestatus(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetCrawlerfileCrawlerfilestandard/{crawlerfileId}/crawlerfilestandard", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetCrawlerfileCrawlerfilestandard(@PathVariable Integer crawlerfileId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				crawlerfileDAO.findCrawlerfileByPrimaryKey(crawlerfileId).getCrawlerfilestandard(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListCrawlerfiles", method = RequestMethod.GET)
	@ResponseBody
	public Object restListCrawlerfiles() {
		return JSONObject.parse(cmiPsonService.toJsonString(crawlerfileService.loadCrawlerfiles(), 2));
	}

	@RequestMapping(value = "/restListCrawlerfilesPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListCrawlerfilesPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = crawlerfilePaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Crawlerfile> crawlerfiles = crawlerfileDAO.findAllCrawlerfiles(startResult,
				cmiPagination.getPaginationSize());
		String crawlerfileString = cmiPsonService.toPsonString(crawlerfiles, 2, cmiPagination);

		return JSONObject.parse(crawlerfileString);
	}

	@RequestMapping("/crawlerfileSelectBox")
	@ResponseBody
	public JSONObject crawlerfileSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Url":
				entitySet = urlService.loadUrlsByIdSet(searchValue);
				break;
			case "Filetype":
				entitySet = filetypeService.loadFiletypesByIdSet(searchValue);
				break;
			case "Crawlerfilestatus":
				entitySet = crawlerfilestatusService.loadCrawlerfilestatussByIdSet(searchValue);
				break;
			case "Crawlerfilestandard":
				entitySet = crawlerfilestandardService.loadCrawlerfilestandardsByIdSet(searchValue);
				break;

			// 被引用键
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Url":
				entitySet = urlDAO.findAllUrls((pageNumber - 1) * paginationSize, paginationSize);
				count = urlService.countUrls();
				break;
			case "Filetype":
				entitySet = filetypeDAO.findAllFiletypes((pageNumber - 1) * paginationSize, paginationSize);
				count = filetypeService.countFiletypes();
				break;
			case "Crawlerfilestatus":
				entitySet = crawlerfilestatusDAO.findAllCrawlerfilestatuss((pageNumber - 1) * paginationSize,
						paginationSize);
				count = crawlerfilestatusService.countCrawlerfilestatuss();
				break;
			case "Crawlerfilestandard":
				entitySet = crawlerfilestandardDAO.findAllCrawlerfilestandards((pageNumber - 1) * paginationSize,
						paginationSize);
				count = crawlerfilestandardService.countCrawlerfilestandards();
				break;

			// 被引用键
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Url":
				entitySet = urlDAO.findUrlByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = urlService.countUrlsByName(queryword);
				break;
			case "Filetype":
				entitySet = filetypeDAO.findFiletypeByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = filetypeService.countFiletypesByName(queryword);
				break;
			case "Crawlerfilestatus":
				entitySet = crawlerfilestatusDAO.findCrawlerfilestatusByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = crawlerfilestatusService.countCrawlerfilestatussByName(queryword);
				break;
			case "Crawlerfilestandard":
				entitySet = crawlerfilestandardDAO.findCrawlerfilestandardByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = crawlerfilestandardService.countCrawlerfilestandardsByName(queryword);
				break;

			// 被引用键
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
